//
//  lxUserRegistViewController.m
//  luodansc
//
//  Created by 倫 星 on 2012/12/03.
//  Copyright (c) 2012年 方正株式会社. All rights reserved.
//

#import "lxUserRegistViewController.h"
#import "lxRegistEntity.h"

@interface lxUserRegistViewController ()
- (void)onRegist:(QButtonElement *)buttonElement;
@end

@implementation lxUserRegistViewController

- (id)init {
    self = [super init];
    if (nil != self) {
        QRootElement *root = [[QRootElement alloc] init];
        root.title = NSLocalizedString(@"register", nil);
        root.grouped = YES;
        root.controllerName = @"lxUserRegistViewController";
        QSection *sectionRegist = [[QSection alloc] init];
        
        sectionRegist.title = NSLocalizedString(@"register", nil);
        
        QEntryElement *userName = [[QEntryElement alloc] initWithTitle:NSLocalizedString(@"username", nil) Value:@"" Placeholder:NSLocalizedString(@"username", nil)];
        userName.key = @"user_name";
        userName.bind = @"textValue:user_name";
        
        QEntryElement *password = [[QEntryElement alloc] initWithTitle:NSLocalizedString(@"passwd", nil) Value:@"" Placeholder:NSLocalizedString(@"passwd", nil)];
        password.key = @"password";
        password.bind = @"textValue:password";
        password.secureTextEntry = YES;
        
        QEntryElement *passwordConfirm = [[QEntryElement alloc] initWithTitle:NSLocalizedString(@"passwd_confirm", nil) Value:@"" Placeholder:NSLocalizedString(@"passwd_confirm", nil)];
        passwordConfirm.key = @"password_confirm";
        passwordConfirm.bind = @"textValue:password_confirm";
        passwordConfirm.secureTextEntry = YES;
        
        QEntryElement *email = [[QEntryElement alloc] initWithTitle:NSLocalizedString(@"email", nil) Value:@"" Placeholder:NSLocalizedString(@"email", nil)];
        email.key = @"email";
        email.bind = @"textValue:email";
        email.keyboardType = UIKeyboardTypeEmailAddress;
        
        [sectionRegist addElement:userName];
        [sectionRegist addElement:password];
        [sectionRegist addElement:passwordConfirm];
        [sectionRegist addElement:email];
        
        QSection *section = [[QSection alloc] init];
        
        QButtonElement *registButton = [[QButtonElement alloc] initWithTitle:NSLocalizedString(@"register", nil)];
        registButton.controllerAction = @"onRegist:";
        
        [section addElement:registButton];
        
        [root addSection:sectionRegist];
        [root addSection:section];
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"register", nil) style:UIBarButtonItemStylePlain target:self action:@selector(regist)];
        self.resizeWhenKeyboardPresented = YES;
        
        self.root = root;
    }
    return self;
}

- (void)regist {
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
    if (YES == [appContainer isExistNet]) {
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        lxRegistEntity *info = [[lxRegistEntity alloc] init];
        [self.root fetchValueUsingBindingsIntoObject:info];
        
        info.user_name = [lxStringUtility stringTrim:info.user_name];
        if ([lxStringUtility isNil:info.user_name]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                            message:NSLocalizedString(@"user_name_is_empty_msg", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
        
        info.password = [lxStringUtility stringTrim:info.password];
        if ([lxStringUtility isNil:info.password]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                            message:NSLocalizedString(@"passwd_is_empty_msg", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
        
        info.password_confirm = [lxStringUtility stringTrim:info.password_confirm];
        if ([lxStringUtility isNil:info.password_confirm]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                            message:NSLocalizedString(@"password_confirm_is_empty_msg", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
        
        info.password_confirm = [lxStringUtility stringTrim:info.password_confirm];
        if (![info.password_confirm isEqualToString:info.password]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                            message:NSLocalizedString(@"password_and_password_confirm_is_diff", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
        
        info.email = [lxStringUtility stringTrim:info.email];
        if ([lxStringUtility isNil:info.email]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                            message:NSLocalizedString(@"email_is_empty_error", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
        
        [self loading:YES];
        [self sendRequest:info.user_name password:info.password email:info.email isStartAsynchronous:YES];
    }
}

- (void)onRegist:(QButtonElement *)buttonElement {
    [self regist];
}

- (void)setQuickDialogTableView:(QuickDialogTableView *)aQuickDialogTableView {
    [super setQuickDialogTableView:aQuickDialogTableView];
    
    self.quickDialogTableView.backgroundView = nil;
    self.quickDialogTableView.backgroundColor = [UIColor colorWithHue:0.1174 saturation:0.7131 brightness:0.8618 alpha:1.0000];
    self.quickDialogTableView.bounces = NO;
    self.quickDialogTableView.styleProvider = self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor orangeColor];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

-(void)cell:(UITableViewCell *)cell willAppearForElement:(QElement *)element atIndexPath:(NSIndexPath *)indexPath{
    cell.backgroundColor = [UIColor colorWithRed:0.9582 green:0.9104 blue:0.7991 alpha:1.0000];
    
    if ([element isKindOfClass:[QLabelElement class]] || [element isKindOfClass:[QWebElement class]]){
        cell.textLabel.textColor = [UIColor colorWithRed:0.6033 green:0.2323 blue:0.0000 alpha:1.0000];
    }
}

- (BOOL)QEntryShouldChangeCharactersInRangeForElement:(QEntryElement *)element andCell:(QEntryTableViewCell *)cell {
    NSLog(@"Should change characters");
    return YES;
}

- (void)QEntryEditingChangedForElement:(QEntryElement *)element andCell:(QEntryTableViewCell *)cell {
    NSLog(@"Editing changed");
}


- (void)QEntryMustReturnForElement:(QEntryElement *)element andCell:(QEntryTableViewCell *)cell {
    NSLog(@"Must return");
    
}

- (void)dealloc {
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (ASIHTTPRequest *)sendRequest:(NSString *)user_name password:(NSString *)password email:(NSString *)email isStartAsynchronous:(BOOL)isStartAsynchronous {
    
    NSString *str_url = [NSString stringWithFormat:@"%@%@?user_name=%@&password=%@&email=%@", service_url, registerUserServlet, user_name, password, email];
    NSURL *url = [NSURL URLWithString:str_url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    
    if (YES == isStartAsynchronous) {
        [request startAsynchronous];
    } else {
        [request startSynchronous];
    }
    return request;
}

- (int)getResponse:(ASIHTTPRequest *)request {
    NSString *responseString = [request responseString];
    
    if (![responseString isKindOfClass:[NSString class]]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    if ([lxStringUtility isNil:responseString]) {
        NSLog(@"reponsedate is nil");
        return NO;
    }
    
    if ([responseString isEqualToString:@"1"]) {
        return 1;
    }
    
    if ([responseString isEqualToString:@"2"]) {
        return 2;
    }
    
    if ([responseString isEqualToString:@"3"]) {
        return 3;
    }
    
    if ([responseString isEqualToString:@"0"]) {
        return 0;
    }
    
    return 4;
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    [self loading:NO];
    int result = [self getResponse:request];
    
    switch (result) {
        case 1: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                            message:NSLocalizedString(@"user_name_is_empty_msg", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
            break;
        case 2: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                            message:NSLocalizedString(@"email_is_empty_error", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
            break;
        case 3: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                            message:NSLocalizedString(@"user_name_isexisted_error", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
            break;
        case 0: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", nil)
                                                            message:NSLocalizedString(@"register_is_successed_msg", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
        default: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                            message:NSLocalizedString(@"register_is_fail_error", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
            break;
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [self loading:NO];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                    message:NSLocalizedString(@"network_conn_failed", nil)
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

@end
